package com.vinoxm.rss.handler;

import com.alibaba.fastjson.JSONObject;
import com.vinoxm.common.auth.server.resource.model.AuthUser;
import com.vinoxm.common.auth.server.resource.service.AuthService;
import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.stereotype.Component;

@Component("permission")
@Log4j2
public class PermissionHandler {

    @Setter(onMethod_ = @Autowired)
    private AuthService authService;

    public boolean checkPermission() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        AuthUser user = null;
        Object credentials = authentication.getDetails();
        if (credentials instanceof OAuth2AuthenticationDetails) {
            Jwt jwt = JwtHelper.decode(((OAuth2AuthenticationDetails) credentials).getTokenValue());
            JSONObject obj = JSONObject.parseObject(jwt.getClaims());
            int userId = (int) obj.getOrDefault("userId", -1);
            if (userId > 0) {
                user = authService.getUser(userId);
            }
        }
        log.info(user);
        return true;
    }
}
